<?php
include_once($project_path.'/class/org/person.class.php5');

class userUser extends fwDbObject
{
	public  $id = null;

	public  $_personId = null;
	/**
	 * @var orgPerson
	 */
	public  $person = null;

	public  $token = '';
	public  $authType = '';
	public  $authId = '';
	public  $displayLogin = '';

	public  $avatar = '';
	public  $avatarColor = '658cdb';

	public  $language = 'fr';

	private $anonymous = false;

	protected $_table_name = 'user_user';
	protected $_table_prefix = 'uu';
	protected $_table_fields = array(
	'uu_i_id' => 'id'
	, 'uu_s_token' => 'token'
	, 'uu_s_authtype' => 'authType'
	, 'uu_s_authid' => 'authId'
	, 'uu_s_login' => 'displayLogin'
	, 'uu_s_avatar' => 'avatar'
	, 'uu_s_avatar_color' => 'avatarColor'
	, 'op_i_id_person' => '_personId'
	, 'fc_s_id_defaultlanguage' => 'language'
	);

	private $_loadedPerson = false;

	/**
	 * Create a new token who will be stored in the cookies
	 *
	 */
	private function buildToken()
	{
		$str = 'ticket_tracking_'.$this->authType.'_'.$this->authId.'_'.uniqid().'_'.time().'_'.microtime();
		$this->token = hash('sha512', $str);
	}

	/**
	 * reteived the users loged on with the current cookie
	 *
	 * @return array list of user order by last connexion desc
	 */
	public static function getPreferedUsers()
	{
		$users_knowned = array();
		if(isset($_COOKIE['current_user']) && $_COOKIE['current_user']!='')
		{
			$users_knowned[] = $_COOKIE['current_user'];
		}

		if(isset($_COOKIE['known_users']))
		{
			$stored_known_users = fwConverter::url2data($_COOKIE['known_users']);
			arsort($stored_known_users);

			foreach ($stored_known_users as $token => $nb_connection)
			{
				$users_knowned[] = $token;
			}
		}
		$users_knowned = array_unique($users_knowned);

		return $users_knowned;
	}

	/**
	 * record the connexion in the prefered users
	 *
	 * @param string $token token id of the user
	 */
	public function setPreferedUser($token)
	{
		if(isset($_COOKIE['known_users']))
		$known_users = fwConverter::url2data($_COOKIE['known_users']);
		else
		$known_users = array();

		if(!is_array($known_users))
		{
			$known_users = array();
		}
		$known_users[$token]=time();
		setcookie('known_users', fwConverter::data2url($known_users	), time() + (10 * 365 * 24 * 60 * 60));
	}

	/**
	 * search the current user in the cookie
	 *
	 * @return userUser
	 */
	public static function autoLogin()
	{
		global $conf;

		if(isset($_COOKIE['current_user']))
		$token = $_COOKIE['current_user'];
		else
		$token = '';

		$user = new userUser();
		$sql = 'SELECT
					*
				FROM
					'.$conf['bdd']['prefix'].'user_user
				WHERE
					uu_s_token=\''.addslashes($token).'\'';

		$user->loadFromRow(fwDb::getRow($sql));
		if($user->id===null)
		{
			return self::getAnonymous();
		}
		return $user;
	}

	public function loadPerson()
	{
		if($this->_loadedPerson) return;
		$p = new orgPerson($this->_personId);
		$p->load();
		$this->person = $p;
		$this->_personId = $p->id;
		$this->_loadedPerson = true;
	}

	/**
	 * Save the datas
	 *
	 */
	public function save()
	{
		if($this->anonymous)
		{
			return false;
		}
		return parent::save();
	}

	public function savePerson()
	{
		if($this->person===null)
		{
			$this->_personId = null;
			return;
		}
		$this->person->save();
		$this->_personId = $this->person->id;
	}

	/**
	 * Display the user as a javascript object
	 *
	 */
	public function displayJS()
	{
		global $project_path;
		$this->loadPerson();
		echo 'current_user = new User('.($this->id===null?"null":$this->id).', "'.$this->language.'", "'.fwConverter::text2JSString(is_dir($project_path.'/view/extrat/avatar/64')?$this->avatar:'').'", "'.fwConverter::text2JSString($this->avatarColor).'");
current_user.anonymous = '.($this->anonymous?'true':'false').';';
		if($this->person != null)
		{
			echo 'current_user.person = new Person("'.fwConverter::text2JSString($this->person->name).'", "'.fwConverter::text2JSString($this->person->firstName).'", "'.fwConverter::text2JSString($this->person->email).'");';
		}
		$this->displayMenuJs();
	}

	/**
	 * Display the menu of the user as a javascript object
	 *
	 */
	public function displayMenuJs()
	{
		if($this->isAnonymous())
		{
			echo 'current_user.menu = new MainMenu();
current_user.menu.push(new Menu("project", "«MENU_PROJECT»"));';
		}
		else
		{
			echo 'current_user.menu = new MainMenu();
current_user.menu.push(new Menu("admin", "«MENU_ADMINISTRATION»"));
current_user.menu.push(new Menu("organization", "«MENU_ORGANIZATION»"));
current_user.menu.push(new Menu("project", "«MENU_PROJECT»"));';
		}
	}

	/**
	 * return true if the user is loged as anonymous
	 *
	 * @return bool
	 */
	public function isAnonymous()
	{
		return $this->anonymous;
	}

	/**
	 * get an anonymous user
	 *
	 * @return userUser
	 */
	public static function getAnonymous()
	{
		$u = new userUser();
		$u->anonymous = true;
		$u->name = '«HOME_ANONYMOUS»';
		$u->avatar = '000';
		$u->person = new orgPerson();
		$u->person->name = '«HOME_ANONYMOUS»';
		return $u;
	}

	/**
	 * log out the current user
	 *
	 */
	public static function logout()
	{
		$_SESSION['current_user'] = self::getAnonymous();
		setcookie('current_user');
	}

	/**
	 * get the user associated to a token
	 *
	 * @param string $authType tytpe of account(gmail, wll..)
	 * @param string $authId id of the account
	 * @param bool $useAuthIdAsName use the authId insted of the person name
	 * @param bool $useAuthIdAsEmail use the authId insted of the person email
	 * @return userUser
	 */
	public static function getUser($authType, $authId, $useAuthIdAsName=false, $useAuthIdAsEmail=false)
	{
		global $project_path, $conf;
		$sql = 'SELECT
			*
		FROM
			'.$conf['bdd']['prefix'].'user_user
		WHERE
			uu_s_authtype=\''.addslashes($authType).'\'
			AND uu_s_authid=\''.addslashes($authId).'\'';
		$user = new userUser();
		$user->loadFromRow(fwDb::getRow($sql));
		if($user->id===null)
		{
			$user->authType = $authType;
			$user->authId = $authId;
			$user->displayLogin = $authId;
			$user->buildToken();
			if(is_dir($project_path.'/view/extrat/avatar/64'))
			{
				$h = opendir($project_path.'/view/extrat/avatar/64');
				$avatars = array();
				while($f = readdir($h))
				{
					if($f=='.' || $f=='..' || $f=='000.png') continue;
					if(!is_file($project_path.'/view/extrat/avatar/64/'.$f)) continue;
					$avatars[] = $f;
				}
	
				$user->avatar = substr($avatars[rand(0, count($avatars)-1)], 0, 3);
			}
			$user->person = new orgPerson();
			if($useAuthIdAsName)
			{
				$user->person->name = preg_replace('/[@]{1}[^@]+$/', '', $authId);
				$user->displayLogin = $user->person->name;
			}
			if($useAuthIdAsEmail)
			{
				$user->person->email = $authId;
			}
			$user->savePerson();

				
			$user->save();
		}
		return $user;
	}

	/**
	 * log in an user
	 *
	 * @param unknown_type $authType
	 * @param unknown_type $authId
	 * @param unknown_type $persistent
	 */
	public static function login($authType, $authId, $persistent=true, $useAuthIdAsName=false, $useAuthIdAsEmail=false)
	{
		$user = self::getUser($authType, $authId, $useAuthIdAsName, $useAuthIdAsEmail);
	
		if($persistent)
		{
			setcookie('current_user', $user->token, time() + (10 * 365 * 24 * 60 * 60));
		}
		else
		{
			setcookie('current_user', $user->token);
		}
		self::setPreferedUser($user->token);
		$_SESSION['current_user'] = $user;
	}


	public function isRoot()
	{
		global $project_path, $conf;
		
		if(isset($conf['appli']['root']['token']))
		{
			return ($conf['appli']['root']['token'] == $_SESSION['current_user']->token);
		}
		else
		{
			include_once($project_path.'/class/fw/login/loginTt.class.php5');
			list($responseOk, $login) = fwLoginTt::processLogin(array('login' => $conf['appli']['root']['login'], 'password' => $conf['appli']['root']['password']));
			if($responseOk)
			{
				$user = self::getUser('tt', $login, false, false);
				$conf['appli']['root']['token'] = $user->token;
				unset($conf['appli']['root']['login']);
				unset($conf['appli']['root']['password']);
				fwTools::saveConfig('appli');
				return ($conf['appli']['root']['token'] == $_SESSION['current_user']->token);
			}
			else
			{
				return false;
			}
		}
	}
	
	public static function checkSession()
	{
		//@todo dans le cas ou l'utilisateur est deconnecté, il faut arreter l'execution des script (penser au dictionnaire)
		if(!isset($_SESSION['current_user']))
		{
			$_SESSION['current_user'] = userUser::autoLogin();
			$_SESSION['current_user']->displayJS();
			echo 'userPageDisplay(new Array("«HOME_PROFIL»", "«HOME_LOGOUT»", "«HOME_LOGIN»", "«HOME_REGISTER»"));';
		}
	}
}
?>